class AuthMiddleware {
    constructor(authService) {
        this.authService = authService;
    }

    // Middleware to check if user is authenticated
    authenticate = async (req, res, next) => {
        try {
            // Try to get sessionId from different sources in order of preference
            let sessionId = null;
            
            // 1. Check express session
            if (req.session && req.session.sessionId) {
                sessionId = req.session.sessionId;
            }
            
            // 2. Check client-side cookie
            if (!sessionId && req.cookies && req.cookies.sessionId) {
                sessionId = req.cookies.sessionId;
                // Restore session in express-session if it exists in cookie but not in session
                req.session.sessionId = sessionId;
            }
            
            // 3. Check Authorization header
            if (!sessionId && req.headers.authorization) {
                sessionId = req.headers.authorization.replace('Bearer ', '');
            }

            console.log('AuthMiddleware - Session ID sources:', {
                authorization: req.headers.authorization,
                cookies: req.cookies?.sessionId,
                session: req.session?.sessionId,
                finalSessionId: sessionId
            });

            if (!sessionId) {
                return res.status(401).json({ error: 'Authentication required' });
            }

            const session = await this.authService.validateSession(sessionId);
            console.log('AuthMiddleware - Session validation result:', session);
            
            if (!session) {
                return res.status(401).json({ error: 'Invalid or expired session' });
            }

            // Attach user to request object
            req.user = session.user;
            req.sessionId = sessionId;
            next();
        } catch (error) {
            console.error('AuthMiddleware - Authentication error:', error);
            res.status(500).json({ error: 'Authentication failed' });
        }
    };

    // Middleware to check if user is admin
    requireAdmin = async (req, res, next) => {
        try {
            await this.authenticate(req, res, () => {
                if (req.user.role !== 'admin') {
                    return res.status(403).json({ error: 'Admin access required' });
                }
                next();
            });
        } catch (error) {
            res.status(500).json({ error: 'Authorization failed' });
        }
    };

    // Optional authentication middleware (doesn't fail if not authenticated)
    optionalAuth = async (req, res, next) => {
        try {
            // Try to get sessionId from different sources in order of preference
            let sessionId = null;
            
            // 1. Check express session
            if (req.session && req.session.sessionId) {
                sessionId = req.session.sessionId;
            }
            
            // 2. Check client-side cookie
            if (!sessionId && req.cookies && req.cookies.sessionId) {
                sessionId = req.cookies.sessionId;
                // Restore session in express-session if it exists in cookie but not in session
                req.session.sessionId = sessionId;
            }
            
            // 3. Check Authorization header
            if (!sessionId && req.headers.authorization) {
                sessionId = req.headers.authorization.replace('Bearer ', '');
            }

            if (sessionId) {
                const session = await this.authService.validateSession(sessionId);
                if (session) {
                    req.user = session.user;
                    req.sessionId = sessionId;
                }
            }
            next();
        } catch (error) {
            // Continue without authentication
            next();
        }
    };
}

module.exports = AuthMiddleware;